package org.lex.reflect.browsing.view.browser;

import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Comparator;

import javax.swing.table.AbstractTableModel;

import org.lex.reflect.browsing.util.ClassHelper;


public class MethodTableModel extends AbstractTableModel {
	private static final String[] COLUMN_NAMES = { "Modifier", "Return", "Name" };
	private static final String[][] EMPTY = new String[0][0];
	private String[][] data = null;
	private int columnCount = 3;

	public MethodTableModel() {
		this.data = EMPTY;
	}

	public void setClass(Class<?> clazz) {
		this.columnCount = 0;
		Method[] all = clazz.getDeclaredMethods();
		data = new String[all.length][];
		for (int i = 0; i < all.length; i++) {
			Method method = all[i];
			Class<?>[] paras = method.getParameterTypes();
			data[i] = new String[paras.length + 3];
			if (columnCount < data[i].length)
				columnCount = data[i].length;
			data[i][0] = Modifier.toString(method.getModifiers());
			data[i][1] = ClassHelper.getTypeName(method.getReturnType());
			data[i][2] = method.getName();
			for (int j = 0; j < paras.length; j++)
				data[i][j + 3] = ClassHelper.getTypeName(paras[j]);
		}
		Arrays.sort(data, new Comparator<String[]>() {
			public int compare(String[] o1, String[] o2) {
				return o1.length - o2.length;
			}
		});
		this.fireTableStructureChanged();
	}

	public String getColumnName(int column) {
		if (column < 3)
			return COLUMN_NAMES[column];
		return "#" + (column - 2);
	}

	public int getColumnCount() {
		return this.columnCount;
	}

	public int getRowCount() {
		return data.length;
	}

	public Object getValueAt(int row, int column) {
		String[] rows = data[row];
		if (column >= rows.length)
			return "-";
		return rows[column];
	}
}
